/*
 * <<
 *  Davinci
 *  ==
 *  Copyright (C) 2016 - 2019 EDP
 *  ==
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  >>
 *
 */

package com.agan.demo.service.impl;


import com.agan.demo.core.model.PaginateWithQueryColumns;
import com.agan.demo.core.model.SqlEntity;
import com.agan.demo.core.utils.CollectionUtils;
import com.agan.demo.core.utils.SqlParseUtils;
import com.agan.demo.core.utils.SqlUtils;
import com.agan.demo.dao.SourceMapper;
import com.agan.demo.dao.ViewMapper;
import com.agan.demo.dto.BaseResp;
import com.agan.demo.dto.ViewExecuteSql;
import com.agan.demo.dto.enums.ReturnCodeEnum;
import com.agan.demo.model.Source;
import com.agan.demo.model.View;
import com.agan.demo.service.ViewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Slf4j
@Service("viewService")
public class ViewServiceImpl implements ViewService {

    @Autowired
    private ViewMapper viewMapper;

    @Autowired
    private SourceMapper sourceMapper;

    @Autowired
    private SqlParseUtils sqlParseUtils;

    @Autowired
    private SqlUtils sqlUtils;

    @Value("${sql_template_delimiter:$}")
    private String sqlTempDelimiter;

    @Override
    public BaseResp<PaginateWithQueryColumns> querySql(ViewExecuteSql viewExecuteSql) {
        BaseResp<PaginateWithQueryColumns> result = BaseResp.buildSuccess();
        //检查sql是否格式正确
        // 解析sql
        SqlEntity sqlEntity = sqlParseUtils.parseSql(viewExecuteSql.getSql(), null, sqlTempDelimiter);
        log.info("sqlEntity:{}",sqlEntity);

        //获取数据源是否存在，初始化
        Long sourceId = viewExecuteSql.getSourceId();
        Source source  = sourceMapper.getById(sourceId);

        SqlUtils sqlUtils = this.sqlUtils.init(source);
        String srcSql = sqlEntity.getSql();
        List<String> querySqlList = sqlParseUtils.getSqls(srcSql, true);

        //结构化Sql
        PaginateWithQueryColumns paginateWithQueryColumns = null;
        if (!CollectionUtils.isEmpty(querySqlList)) {
            for (String sql : querySqlList) {
                sql = SqlParseUtils.rebuildSqlWithFragment(sql);
                try {
                    paginateWithQueryColumns = sqlUtils.syncQuery4Paginate(sql, null, null, null, viewExecuteSql.getLimit(),
                            null);
                } catch (Exception e) {
                    log.error("error",e);
                }
            }
        }
        //解析sql，获取结果集预览
        log.info("paginateWithQueryColumns:{}",paginateWithQueryColumns);
        log.info("paginateWithQueryColumns result:{}",paginateWithQueryColumns.getResultList());
        result.setMsg(ReturnCodeEnum.SUCCESS.getMessage());
        result.setStatus(ReturnCodeEnum.SUCCESS.getCode());
        result.setData(paginateWithQueryColumns);
        return result;
    }
}

